package com.xuerhua.yxt.listener;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.xuerhua.yxt.common.AdminUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.model.GradeInfo;
import com.xuerhua.yxt.model.OrganizeDepart;
import com.xuerhua.yxt.model.SubjectInfo;
import com.xuerhua.yxt.service.IGradeInfoService;
import com.xuerhua.yxt.service.IOrganizeDepartService;
import com.xuerhua.yxt.service.ISubjectInfoService;
import com.xuerhua.yxt.wechat.utils.WechatGlobalMap;

public class SystemInitListener implements  ApplicationListener<ContextRefreshedEvent>{
	Logger log = LoggerFactory.getLogger(SystemInitListener.class);
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		ApplicationContext applicationContext = event.getApplicationContext();
		initOrganizeDepart(applicationContext);
		initSubject(applicationContext);
		initGrade(applicationContext);
	}
	
	/**
	 * 初始化组织架构
	 * @param applicationContext
	 */
	private void initOrganizeDepart(ApplicationContext applicationContext) {
		IOrganizeDepartService organizeDepartService = (IOrganizeDepartService) applicationContext.getBean("organizeDepartService");
		Map<String, OrganizeDepart> map = new HashMap<>();
		List<OrganizeDepart> list = organizeDepartService.selectListByParam(new OrganizeDepart());
		for(OrganizeDepart role : list) {
			map.put(String.valueOf(role.getId()), role);
		}
		WechatGlobalMap.put(Const.CACHE_ORGANIZE_DEPART, map);
	}
	
	/**
	 * 初始化学科
	 * @param applicationContext
	 */
	private void initSubject(ApplicationContext applicationContext) {
		ISubjectInfoService subjectInfoService = (ISubjectInfoService) applicationContext.getBean("subjectInfoService");
		List<SubjectInfo> list = subjectInfoService.selectList(new SubjectInfo().getSchoolId());
		Map<Integer, String> map = new LinkedHashMap<>();
		for(SubjectInfo subject : list) {
			map.put(subject.getId(), subject.getSubject());
		}
		WechatGlobalMap.put(Const.CACHE_SUBJECT, map);
	}
	
	/**
	 * 初始化年级
	 * @param applicationContext
	 */
	private void initGrade(ApplicationContext applicationContext) {
		IGradeInfoService gradeInfoService = (IGradeInfoService) applicationContext.getBean("gradeInfoService");
		List<GradeInfo> list = gradeInfoService.selectList();
		Map<Integer, String> map = new LinkedHashMap<>();
		for(GradeInfo subject : list) {
			map.put(subject.getId(), subject.getGradeName());
		}
		WechatGlobalMap.put(Const.CACHE_GRADE, map);
	}
}
